package net.expectx.common.single.third.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import io.netty.handler.codec.http.HttpMethod;
import net.expectx.common.single.base.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lijian
 * 极光推送工具类
 */
public class PushUtil {
    protected static final Logger LOG = LoggerFactory.getLogger(PushUtil.class);
    protected static final String APP_KEY = "ed18a213870cbab520a7a230";
    protected static final String MASTER_SECRET = "ab1a221791d7fb6cf49d551f";
    public static void main(String[] args) throws Exception{
        Map<String,String>extras= Maps.newHashMapWithExpectedSize(7);
        extras.put("orderId","11111");
        extras.put("type","orderPay");
        extras.put("paySuccess","true");
       for(Integer i=0;i<1;i++){
          // net.expectx.common.base.BaseResult baseResult=sendPushWithAll("您有新的订单","订单:英国进口 麦维他（Mcvitie's）原味全麦粗粮酥性消化饼干 400g 早餐下午茶零食",extras);
           BaseResult baseResult=sendPushWithAlias("9_ED2965CDF644403CB51B100A0C767B64","您有新的订单","订单:英国进口 麦维他（Mcvitie's）原味全麦粗粮酥性消化饼干 400g 早餐下午茶零食",extras);
           System.out.println(baseResult);
           Thread.sleep(1000*5);
       }
    }

    /**
     * 根据设备别名推送消息
     * @param alias         別名
     * @param title         标题
     * @param content       内容
     * @param extras        扩展参数
     */
    public static BaseResult sendPushWithAlias(String alias, String title, String content, Map<String, String> extras) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
                null, clientConfig);
        final boolean flag=false;
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));

            PushPayload payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(alias))
                    .setNotification(buildNotification(title,content,extras))
                    .build();
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    LOG.info("发送结果: " + responseWrapper.responseContent);

                }
            });
            return new BaseResult(true,"消息推送成功",null);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return new BaseResult(false,"系统错误:"+e.getLocalizedMessage(),null);
        }
    }

    /**
     * 根据设备组推送消息
     * @param tag           设备组
     * @param title         标题
     * @param content       内容
     * @param extras        扩展参数
     */
    public static void sendPushWithTag(String tag,String title,String content, Map<String, String> extras) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
                null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));

            PushPayload payload = PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.tag(tag))
                    .setNotification(buildNotification(title,content,extras))
                    .build();
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    LOG.info("Got result: " + responseWrapper.responseContent);
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

    /**
     * 向所有设备推送消息
     * @param title         标题
     * @param content       内容
     * @param extras        扩展参数
     */
    public static BaseResult sendPushWithAll(String title,String content, Map<String, String> extras) {
        ClientConfig config = ClientConfig.getInstance();
        config.setPushHostName("https://api.jpush.cn");

        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(buildNotification(title,content,extras))
                .build();

        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("发送结果- " + result);
            return new BaseResult(true,"消息推送成功",null);

        } catch (APIConnectionException e) {
            return new BaseResult(false,"系统错误:"+e.getLocalizedMessage(),null);
        } catch (APIRequestException e) {
            return new BaseResult(false,"系统错误:"+e.getErrorMessage(),null);
        }
    }

    /**
     * 构建通知
     * @param title
     * @param content
     * @param extras
     * @return
     */
    private static Notification buildNotification(String title,String content,Map extras){
        return  Notification.newBuilder()
                .setAlert(content)
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setTitle(title)
                        .addExtras(extras).build())
                .addPlatformNotification(IosNotification.newBuilder()
                        .incrBadge(1)
                        .addExtra("extras", JSON.toJSONString(extras)).build())
                .build();
    }


}
